package com.taobao.askwho.db.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.taobao.askwho.db.base.MysqlRouteBase;
import com.taobao.askwho.po.PersonInfo;
import com.taobao.askwho.utils.DateUtil;

public class PersonInfoDao extends MysqlRouteBase {
	private static  Logger logger = Logger.getLogger(PersonInfoDao.class);
	
	public void addPersonInfo(PersonInfo info) throws SQLException {
		String sql = "INSERT INTO person_info(UUID,person_name,wangwang,md5,updatetime,createtime) VALUE (?,?,?,?,?,?)";
		this.execute(sql, new Object[]{info.getUuid(), info.getPersonName(),info.getWangwang(),info.getMd5(),
				info.getUpdateTime(), info.getCreateTime()});
	}
	
	public void deletePersonInfo(String uuid) throws SQLException {
		String sql = "delete from person_info where uuid = ?";
		this.execute(sql, new Object[]{uuid});
	}	

	public List<PersonInfo> getRecentlyPerson(int limit, int size) {
		final List<PersonInfo> list = new ArrayList<PersonInfo>();
		String sql = "SELECT * FROM person_info ORDER BY updatetime DESC LIMIT ?,?";
		try {
			this.query(sql, new Object[]{limit,size}, new SqlCallBack() {
				@Override
				public void readerRows(ResultSet rs) throws Exception {
					PersonInfo info = new PersonInfo();
					setValueForPo(info,rs);
					list.add(info);
				}
			});
		} catch (Exception e) {
			logger.error("",e);
		}
		return list;
	}	
	
	public Map<String, PersonInfo> getPersonListByUuidList(List<String> uuidList) {
		//暂时做两次查询,把结果做合并
		String inStr = "";
		for(String uuid: uuidList) {
			inStr += "'" + uuid + "',";
		}
		if(uuidList.size() > 0)
			inStr = inStr.substring(0,inStr.length() - 1);
		else
			return new HashMap<String, PersonInfo>();		
		
		final Map<String, PersonInfo> map = new HashMap<String, PersonInfo>();
		String sql = "SELECT * FROM person_info where uuid in (" + inStr + ")";
		try {
			this.query(sql, new SqlCallBack() {
				@Override
				public void readerRows(ResultSet rs) throws Exception {
					PersonInfo info = new PersonInfo();
					setValueForPo(info,rs);
					map.put(info.getUuid(), info);
				}
			});
		} catch (Exception e) {
			logger.error("",e);
		}
		return map;
	}		
	
	private void setValueForPo(PersonInfo info, ResultSet rs) throws SQLException {
		info.setUuid(rs.getString("uuid"));
		info.setPersonName(rs.getString("person_name"));
		info.setWangwang(rs.getString("wangwang"));
		info.setMd5(rs.getString("md5"));
		info.setCreateTime(new Date());	
		info.setUpdateTime(new Date());
		info.setCreateTimeStr(DateUtil.cutLastNumOfSqlTimeString(rs.getString("createtime")));
		info.setUpdateTimeStr(DateUtil.cutLastNumOfSqlTimeString(rs.getString("updatetime")));		
	}	
}
